package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 预约设置服务
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    //批量导入预约设置
    @Override
    public void add(List<OrderSetting> list) {
        if (list != null && list.size()>0) {
            for (OrderSetting orderSetting : list) {
                //判断当前数据是否已经进行了预约设置
                long countByOrderData = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if (countByOrderData > 0){
                    //已经进行了预约设置,所以执行更新操作
                    orderSettingDao.editNumberByOrderData(orderSetting);
                }else {
                    //没有进行预约设置,执行插入操作
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }

    //根据月份查询对应的预约设置数据
    @Override
    public List<Map> getOrderSettingByMonth(String date) {  //date的格式yyyy-MM
        String begin = date + "-1";  //格式为2020-7-1
        String end = date + "-31";  //格式为2020-7-1
        Map<String, String> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        //调用dao层,根据日期范围查询预约设置数据
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);
        List<Map> result = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (OrderSetting orderSetting : list) {
                Map<String, Integer> map1 = new HashMap<>();
                map1.put("date",orderSetting.getOrderDate().getDate());
                map1.put("number", orderSetting.getNumber());
                map1.put("reservations",orderSetting.getReservations());
                result.add(map1);
            }
        }
        return result;
    }

    //根据日期修改可预约的人数
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        Date orderDate = orderSetting.getOrderDate();
        //先根据日期查询是否已经有预约人数
        long count = orderSettingDao.findCountByOrderDate(orderDate);
        if (count > 0){
            //已经预约了,执行更新操作
            orderSettingDao.editNumberByOrderData(orderSetting);
        }else {
            //没有预约,进行添加预约人数
            orderSettingDao.add(orderSetting);
        }
    }
}
